﻿using System;
using System.Diagnostics;
using System.Threading;

namespace SharpML.Api.Extensions
{
    public static class Threads
    {
        /// <summary>
        /// I normally do not condone using sleep to magically solve problems, but in this case
        /// I am (almost indiscriminately) pushing off execution into the .net thread pool.
        /// This function is designed to give each thread ample opportunity to complete it's task
        /// based on a pump-action, which is likely a call to DoEvents.  I've done my best to 
        /// keep forms reference out of API though, I'd like to be cross-platform compatible 
        /// as a general rule, so instead we'll just pass in the delegate.
        /// </summary>
        /// <param name="thread"></param>
        /// <param name="pumpAction"></param>
        public static void PumpYieldAll( this Thread thread, Action pumpAction )
        {
            int workerThreads = Process.GetCurrentProcess().Threads.Count;

            for( int waitCycle = 0; waitCycle < workerThreads; waitCycle++ )
            {
                // Pump 
                pumpAction();

                // Yield for one whole slice
                Thread.Sleep( 15 );

                // Pump 
                pumpAction();
            }
        }

    }
}
